package com.lynn.salary.util;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.lynn.salary.dto.CacheDTO;

public class Cache {

	public static Cache instance = new Cache();
	private long expireTime = 1000 * 60 * 5;//默认清理60秒前的数据   每次get操作触发清理过期缓存
	private Cache() {
	}

	private Map<String, CacheDTO> cacheSearchCondition = new HashMap<String, CacheDTO>();

	public static Cache getInstance() {
		return instance;
	}

	public static void setInstance(Cache instance) {
		Cache.instance = instance;
	}

	// public Map<String, CacheDTO> getCacheSearchCondition() {
	// return cacheSearchCondition;
	// }
	//
	// public void setCacheSearchCondition(Map<String, CacheDTO>
	// cacheSearchCondition) {
	// this.cacheSearchCondition = cacheSearchCondition;
	// }
	public Object getSearchConditionByTag(String searchTag) {
		return getSearchConditionByTag(searchTag, false);
	}

	public Object getSearchConditionByTag(String searchTag, boolean del) {
		clearExpireCache();
		CacheDTO o = this.cacheSearchCondition.get(searchTag);

		if (o != null && del) {
			this.cacheSearchCondition.remove(searchTag);
			return o.getCache();
		} else if (o != null && !del) {
			return o.getCache();
		}
		return null;
	}

	public void cacheSearchCondition(String searchTag, Object o) {
		CacheDTO co = new CacheDTO();
		co.setCache(o);
		co.setTimestamp(new Date().getTime());
		cacheSearchCondition.put(searchTag, co);
		clearExpireCache();
	}

	private void clearExpireCache() {
		long curtime = new Date().getTime();
		for (String key : cacheSearchCondition.keySet()) {
			CacheDTO co = cacheSearchCondition.get(key);

			long d = co.getTimestamp();
			long expireTime = this.expireTime;   //8秒后清理
			if ((curtime - d) > expireTime) {
				cacheSearchCondition.remove(key);
			}
		}
	}
}
